<template>
  <div class="modifyPrice" @click.stop="aotuTab = false">
    <div class="header">
      <el-button size="mini" type="primary" @click="preservation('A')">
        {{ $t('btn.save') }}
      </el-button>
    </div>
    <el-tabs v-model="activeName">
      <el-tab-pane :label="$t('market.info')" name="modifyPrice" class="layout">
        <jc-form ref="zrf" :option-value="optionValue" :options="options">
          <el-autocomplete
            v-model.trim="optionValue.fdataValue"
            highlight-first-item
            popper-class="my-autocomplete"
            :fetch-suggestions="querySearch18"
            class="input-width"
            size="mini"
            @focus="getBasicUnit('SXTJ_PAREASON')"
            @select="selUnit"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              @click="unitVisabled=true"
            />
            <template slot-scope="{ item }">
              <div class="name">{{ item.fname }}</div>
            </template>
          </el-autocomplete>
        </jc-form>
        <div style="margin-bottom: 5px">
          <el-button
            :disabled="isDisabled"
            size="mini"
            @click="insertHang"
          >{{ $t('btn.newHang') }}<!--新增行--></el-button>
          <el-button size="mini" :disabled="isDisabled" @click="delHang">{{ $t('btn.delHang') }}<!--删除行--></el-button>
          <el-button
            size="mini"
            :disabled="isDisabled"
            @click="batchFill"
          >{{ $t('btn.batchFill') }}<!--批量填充--></el-button>
        </div>
        <div>
          <jc-table
            :table-data="modifyPriceTable"
            :table-header="modifyPriceHeader"
            table-height="calc(100vh - 290px)"
            serial
            @cellClick="cellClick"
            @rowClick="rowClick"
          >
            <el-table-column
              :label="$t('market.priceList')"
              prop="fname"
              align="center"
              width="130px"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.fpriceList"
                  size="mini"
                  :disabled="isDisabled"
                >
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="handlePriceList(scope.$index)"
                  />
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('market.custname')"
              prop="fsupplier"
              align="center"
              width="120"
              show-overflow-tooltip
            />
            <el-table-column
              :label="$t('market.fmaterial')"
              prop="fnumber"
              align="center"
              width="150px"
            >
              <template slot-scope="scope">
                <el-input
                  v-model.trim="scope.row.fnumber"
                  size="mini"
                  @input="getAtuo(scope.$index, scope.row.fnumber)"
                >
                  <i
                    slot="prefix"
                    class="iconfont icon-jin-rud-ao-bo"
                    @click="sonJumpMateriel(scope.row.fnumber)"
                  />
                  <i
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                    @click="handleMateriel(scope.row, scope.$index)"
                  />
                </el-input>
                <div v-if="aotuTab && scope.$index === tableIndex" :class="tableIndex<6 ? 'tabPosit': 'tabPosit1'">
                  <number-code :fnumber="fnumber1" :materielid="materielid" bom-code="1" @material="materielSelectRow" />
                </div>
              </template>
            </el-table-column>
            <template v-slot:tagSlot="col">
              <el-input-number
                v-model="col.scope.row.fafterPrice"
                size="mini"
                :precision="4"
                :step="0.0001"
                :min="0.0"
              />
            </template>
            <!-- 生效时间 -->
            <template v-slot:btnState="col">
              <el-date-picker
                v-model="col.scope.row.feffectiveDate"
                type="date"
                value-format="yyyy-MM-dd"
                size="mini"
                :disabled="isDisabled"
                style="width: 163px"
              />
            </template>
            <!-- 失效时间 -->
            <template v-slot:btnStates="col">
              <el-date-picker
                v-model="col.scope.row.fexpiryDate"
                type="date"
                value-format="yyyy-MM-dd"
                size="mini"
                :disabled="isDisabled"
                style="width: 163px"
              />
            </template>
          </jc-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!--    销售价目列表-->
    <sal-price v-if="openPriceList" @client="priceListSelectRow" />
    <!--    物料编码列表-->
    <materiel v-if="openMaterial" :materielid="materielid" @client="materielSelectRow" />
    <!--  数据字典弹窗  -->
    <unit v-if="unitVisabled" :msg="funit" @unit="selUnit" />
  </div>
</template>

<script>
import jcForm from '@/components/Form'
import {
  insertTPurPat,
  queryTPurPatDetailList
} from '@/api/marketManage/salesPicing'
import jumpMateriel from '@/components/JumpMateriel'
import { toMxAmina } from '@/components/ToMxamineState'
import autocomplete from '@/views/market/marketManage/createMarkerOrder/components/autocomplete'

export default {
  name: 'SalesPicingAdd',
  components: {
    salPrice: () => import('@/views/market/salesPicing/component/salPrice'),
    materiel: () => import('@/views/market/salesPicing/component/materiel'),
    jcForm,
    numberCode: () => import('@/components/NumberCode'),
    unit: () => import('@/views/basic/createMateriel2/components/unit')
  },
  mixins: [jumpMateriel, autocomplete],
  props: {
    modify: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      radio2: '新增',
      activeName: 'modifyPrice',
      fnumber1: '',
      unitVisabled: false,
      funit: 'SXTJ_PAREASON', // 调价原因
      openModifyPrice: false, // 采购调价原因列表弹窗
      openPriceList: false, // 销售价目列表弹窗
      openMaterial: false, // 物料编码弹窗
      materielid: '',
      teamList: [], // 组织数
      isDisabled: false,
      aotuTab: false,
      modifyPriceTable: [
        {
          fid: this.modify.fid || '', // 价目ID
          fmaterialId: '', // 物料ID
          fname: this.modify.fname || '', // 价目表
          fnumber: '', // 物料编码
          fprice: '', // 调前单价
          fafterPrice: '', // 调后单价
          fsupplier: this.modify.fsupplier || '', // 客户名称
          fcurrency: this.modify.fcurrency || '', // 币别
          fdescripTion: '', // 描述
          fspecificaTion: '', // 规格型号
          feffectiveDate: new Date(), // 生效时间
          fexpiryDate: '2100-01-01' // 失效时间
        }
      ], // 调价表数据
      modifyPriceHeader: [
        { label: this.$t('shop.fname2'), prop: 'fname' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion' },
        { label: this.$t('market.fmodel2'), prop: 'fmodel' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion' },
        { label: this.$t('market.funit'), prop: 'funit', width: 80 },
        { label: this.$t('market.currency2'), prop: 'fcurrency', width: 60 },
        { label: this.$t('market.formerPrice1'), prop: 'fprice', width: 80 },
        { label: this.$t('market.afterPrice1'), type: 'tag', prop: 'fafterPrice', width: '100' },
        { label: this.$t('market.effectiveDate'), prop: 'feffectiveDate', type: 'state', width: '120' },
        { label: this.$t('market.expiryDate'), prop: 'fexpiryDate', type: 'states', width: '120' }
      ],
      optionValue: {}, // 表单值
      options: {}, // 表单控件
      tableIndex: 0, // 表格序号
      nary: []
    }
  },
  created() {
    if (this.$route.query.fid) {
      this.optionValue.fid = this.$route.query.fid
      this.getFormTo()
    } else {
      this.getForm()
    }
  },
  methods: {
    // 输入物料编码
    getAtuo(index, fnumber) {
      this.tableIndex = index
      this.aotuTab = true
      var vm = this
      clearTimeout(vm.timer) // 清除未执行的代码，重置回初始化状态
      vm.timer = setTimeout(() => {
        this.fnumber1 = fnumber
      }, 1000)
    },
    // 保存
    preservation(ev) {
      const validDate = this.$refs.zrf.handleRefData()
      if (!validDate) {
        return
      }
      for (const ITEM of this.modifyPriceTable) {
        if (
          !ITEM.fid ||
          !ITEM.fmaterialId
        ) {
          this.$message.warning('表格不能为空,或表格值不能为0')
          return
        }
      }
      this.nary = []
      const DETAILS = this.modifyPriceTable.map(item => {
        this.nary.push(item.fnumber)
        const {
          fmaterialId,
          fafterPrice,
          fprice,
          fname,
          funitId,
          fsupplierId,
          fcurrencyId,
          feffectiveDate,
          fexpiryDate,
          fsrcentryId,
          fcustid
        } = item
        return {
          fname,
          funitId,
          fsupplierId,
          fcurrencyId,
          fsrcentryId,
          fpriceListId: item.fid,
          fmaterialId,
          fprice,
          fafterPrice,
          feffectiveDate,
          fexpiryDate,
          fcustid
        }
      })
      const nary = this.nary.sort()
      for (const index in this.nary) {
        const index1 = Number(index) + 1 * 1
        if (nary[index] === nary[index1]) {
          this.$message.warning('重复的物料：' + nary[index])
          return false
        }
      }
      const { fname, fdescription, fpaReason, fid, fdate } = this.optionValue
      const DATA = {
        fid,
        fdate,
        fname,
        fdescription,
        fpaReason,
        fdocumentStatus: ev, // 保存A,提交B
        details: DETAILS
      }
      insertTPurPat(DATA)
        .then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          this.optionValue.billCode = res.data.fbillNo
          this.optionValue.fid = res.data.fid
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          this.getForm()
          this.modifyPriceTable = []
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          // 跳转到修改页面
          this.$router.push({ path: `/salesPicingEdit/${res.data}` })
          this.$message({ showClose: true, message: res.message, type: 'success' })
        })
        .catch(error => {
          this.$message.error(error)
        })
    },
    // 价目表
    handlePriceList(index) {
      this.tableIndex = index
      this.openPriceList = true
    },
    // 获取价目表
    priceListSelectRow(item) {
      if (item.fid) {
        const { fname, fsupplier, fisIncludedTax, fcurrency, fid, fcustid, fcurrencyId } = item
        const modifyPriceTable = this.modifyPriceTable[this.tableIndex]
        modifyPriceTable.fpriceList = fname
        modifyPriceTable.fsupplier = fsupplier
        modifyPriceTable.fisIncludedTax = fisIncludedTax
        modifyPriceTable.fcurrency = fcurrency
        modifyPriceTable.fcurrencyId = fcurrencyId
        modifyPriceTable.fid = fid
        modifyPriceTable.fcustid = fcustid
        // 物料编码
        modifyPriceTable.fmaterialId = ''
        modifyPriceTable.fnumber = ''
      }
      this.openPriceList = false
    },
    // 获取物料编码
    materielSelectRow(item) {
      if (item.fmaterialId) {
        const modifyPriceTable = this.modifyPriceTable[this.tableIndex]
        const {
          fmaterialId,
          fnumber,
          fname,
          fmodel,
          funit,
          funitId,
          fspecificaTion,
          fdescripTion,
          fprice,
          fsrcentryId
        } = item
        modifyPriceTable.fmaterialId = fmaterialId
        modifyPriceTable.fnumber = fnumber
        modifyPriceTable.fname = fname
        modifyPriceTable.fmodel = fmodel
        modifyPriceTable.funit = funit
        modifyPriceTable.funitId = funitId
        modifyPriceTable.fspecificaTion = fspecificaTion
        modifyPriceTable.fdescripTion = fdescripTion
        modifyPriceTable.fprice = fprice
        modifyPriceTable.fsrcentryId = fsrcentryId
      }
      this.openMaterial = false
      this.aotuTab = false
    },
    // 获取物料编码
    async handleMateriel(row, index) {
      this.tableIndex = index
      if (!row.fid) {
        this.$message.warning('价目表未选择或数据出错,请重新选择')
        return
      }
      this.materielid = row.fid
      this.openMaterial = true
    },
    // 调价原因
    selUnit(ev) {
      if (ev.fid) {
        this.optionValue.fdataValue = ev.fname
        this.optionValue.fpaReason = ev.fid
      }
      this.unitVisabled = false
    },
    // 删除行数据
    handleDelete(index) {
      this.modifyPriceTable.splice(index, 1)
      this.$message.success('删除行成功')
    },
    // 获取表格
    async getForm() {
      this.optionValue = {
        fdate: new Date(),
        fdocumentStatus: '创建', // 单据状态
        fdataValue: '', // 调价原因名称
        fpaReason: '', // 调价原因id
        fname: '', // 名称
        billCode: '', // 单据编号
        fdescription: '' // 描述
      }
      this.options = {
        fpaReason: {
          label: this.$t('market.paReason'),
          type: 'slot',
          span: 6
        },
        fname: {
          label: this.$t('shop.name1'),
          span: 6,
          rules: [{ required: true }]
        },
        billCode: {
          label: this.$t('market.billNo'),
          span: 6,
          disabled: 'disabled'
        },
        fdocumentStatus: {
          label: this.$t('market.documentstatus'),
          type: 'tag',
          labelWidth: '100px',
          span: 6,
          disabled: 'disabled'
        },
        fdate: {
          label: this.$t('market.placedate'),
          type: 'date',
          span: 6
        },
        fdescription: {
          label: this.$t('market.descrip'),
          span: 6
          // rules: [{ required: true }]
        }
      }
    },
    // 获取详情(复制)
    async getFormTo() {
      const { data: RES } = await queryTPurPatDetailList({
        fid: this.optionValue.fid
      })
      this.modifyPriceTable = RES.detail
      // const { data: TEAMlIST } = await queryTOrgOrganizationsL()
      // this.teamList = TEAMlIST.map(item => {
      //   const { fname: label, fpkId: value } = item
      //   return { label, value }
      // })
      const { fdataValue, fid, fname, fdescripTion, fdocumentStatus, fdate, fpareason } = toMxAmina(RES)
      this.optionValue = {
        fid,
        fdate,
        fdocumentStatus, // 状态
        fdataValue, // 调价原因名称
        fpareason, // 调价原因id
        fname, // 名称
        billCode: '', // 单据编号
        fdescription: fdescripTion // 描述
      }
      this.optionValue.fdocumentStatus = '创建'
      this.options = {
        fdataValue: {
          label: this.$t('market.paReason'),
          type: 'slot',
          disabled: this.isDisabled,
          span: 6
        },
        fname: {
          label: this.$t('shop.name1'),
          span: 6,
          disabled: this.isDisabled
        },
        billCode: {
          label: this.$t('market.billNo'),
          span: 6,
          disabled: 'disabled'
        },
        fdocumentStatus: {
          label: this.$t('market.documentstatus'),
          span: 6,
          disabled: 'disabled'
        },
        fdate: {
          type: 'date',
          label: this.$t('market.placedate'),
          disabled: this.isDisabled,
          span: 6
        },
        fdescription: {
          label: this.$t('market.descrip'),
          span: 12,
          disabled: this.isDisabled
        }
      }
    },
    // 点击单元格
    cellClick(row, column, cell, event) {
      this.property = column.property
      this.subscript = row.index
    },
    // 批量填充
    batchFill() {
      const item = this.modifyPriceTable[this.subscript][this.property]
      this.modifyPriceTable.map((res, index) => {
        if (index >= this.subscript) {
          res[this.property] = item
          if (this.property === 'fname') {
            res.fid = this.modifyPriceTable[0].fid
            res.fpriceList = this.modifyPriceTable[0].fpriceList
            res.fsupplier = this.modifyPriceTable[0].fsupplier
            res.fcustid = this.modifyPriceTable[0].fcustid
            res.fcurrency = this.modifyPriceTable[0].fcurrency
            res.fcurrencyId = this.modifyPriceTable[0].fcurrencyId
          }
        }
      })
    },
    // 单击行
    rowClick(row) {
      this.indexSelf = row.index
    },
    // 删除行
    delHang() {
      this.modifyPriceTable.splice(this.indexSelf, 1)
    },
    // 新增插入行
    insertHang() {
      const data = {
        funit: '',
        fid: this.modify.fid || '', // 价目ID
        fmaterialId: '', // 物料ID
        fname: this.modify.fname || '', // 价目表
        fnumber: '', // 物料编码
        fafterPrice: '', // 调后单价
        fsupplier: this.modify.fsupplier || '', // 供应商名称
        fcurrency: this.modify.fcurrency || '', // 币别
        fdescripTion: '', // 描述
        fspecificaTion: '', // 规格型号
        fprice: '', // 调前单价
        feffectiveDate: new Date(), // 生效时间
        fexpiryDate: '2100-01-01' // 失效时间
      }
      this.modifyPriceTable.push(data)
    }
  }
}
</script>

<style scoped lang="scss">
.modifyPrice {
  @include listBom;
  display: flex;
  flex-direction: column;

  .header {
    margin-bottom: 0.62vh;
  }
  .tabPosit {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: 3.8vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
  .tabPosit1 {
    padding: 5px;
    box-shadow: 0 0 2px #aaa;
    position: absolute;
    top: -25.69vh;
    left: 0;
    background-color: rgba(255, 255, 255, 1);
    z-index: 9999;
  }
  .layout {
    display: flex;
    flex-direction: column;

    .input-width {
      width: 185px;
    }
  }
}

.el-input__icon {
  cursor: pointer;
}

.icon-jin-rud-ao-bo {
  cursor: pointer;

  &:hover {
    color: #409eff;
  }
}
</style>
